﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using SlamCms.SharePoint.Core;
using System.Web;
using SlamCms.SharePoint.Data;
using System.Data.EntityClient;
using System.Linq;
using System.Collections.Generic;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;

namespace SlamCms.SharePoint.Publishing.WebParts
{
	public partial class PublishingSitesLinksControl : UserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			//string userName = "aws01\\grascioni";
			//string userName = "aws01\\awellenstein";
			string userName = HttpContext.Current.User.Identity.Name.Contains("|") ? HttpContext.Current.User.Identity.Name.Split('|').Last() : HttpContext.Current.User.Identity.Name;
			var user = (from u in SlamCmsContext.Data.Users
						where u.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase)
						select u).FirstOrDefault();

			//SPWeb currentSite = SPControl.GetContextWeb(HttpContext.Current);
			if (user != null)
			{
				if (user.Groups != null)
				{
					var groups = user.Groups.Where(g => g.Edit).ToList();
					//List<SiteItem> sitesList = new List<SiteItem>();
					//List<SlamCms.Data.Site> resultSites = new List<SlamCms.Data.Site>();
					List<SiteItem> sitesList = new List<SiteItem>();
					List<string> siteUrls = new List<string>();
					foreach (SlamCms.Data.Group g in groups)
					{
						if (g.Sites != null)
						{
							foreach (SlamCms.Data.Site site in g.Sites)
							{
								var zone = site.Zones.FirstOrDefault();
								if (zone != null)
								{
									string siteColUrl = site.SiteCollection != null ? site.SiteCollection.ServerRelativeUrl : String.Empty;
									var item = new SiteItem() { Url = siteColUrl + site.Url, Title = zone.Title + ": " + site.Title };
									if (!siteUrls.Contains(item.Url))
									{
										siteUrls.Add(item.Url);
										sitesList.Add(item);
									}
								}
							}
						}

					}

					linksRepeater.DataSource = sitesList.OrderBy(s => s.Title);
					linksRepeater.DataBind();
				}
			}
		}
	}

	public class SiteItem
	{

		public string Url { get; set; }
		public string Title { get; set; }
	}
}
